import request from '@/utils/request';

export interface ChatHistory {
  id: number;
  title: string;
  userId: number;
  roomId: string;
  createTime: string;
  updateTime: string;
}

// 定义会话历史完整数据接口，包含消息内容
export interface SessionHistoryData {
  id: number;
  title: string;
  userId: number;
  roomId: string;
  createTime: string;
  updateTime: string;
  messages: Array<{
    id: number;
    value: string;
    user: string;
    isInterrupted?: boolean;
    createTime: string;
  }>;
}

// 聊天消息请求接口
export interface MessageRequest {
  sessionId: number;
  text: string;
  user: string;
  paragraph?: boolean;
  definite?: boolean;
  isInterrupted?: boolean;
}

export async function getChatHistory() {
  return request<ChatHistory[]>({
    url: '/session/list',
    method: 'GET',
  });
}

export async function createChatHistory(data: Partial<ChatHistory>) {
  return request<ChatHistory>({
    url: '/session/create',
    method: 'POST',
    data,
  });
}

export async function deleteChatHistory(id: number) {
  return request<boolean>({
    url: `/session/delete/${id}`,
    method: 'DELETE',
  });
}

export async function updateChatHistory(data: Partial<ChatHistory>) {
  return request<boolean>({
    url: '/session/update',
    method: 'PUT',
    data,
  });
}

export async function getChatHistoryDetail(id: number) {
  return request<SessionHistoryData>({
    url: `/session/detail/${id}`,
    method: 'GET',
  });
}

/**
 * 保存聊天消息
 * @param data 消息请求对象
 * @returns 是否保存成功
 */
export async function addChatMessage(data: MessageRequest) {
  return request<boolean>({
    url: '/session/message/add',
    method: 'POST',
    data,
  });
}

/**
 * 生成RTC访问令牌
 * @param roomId 房间会话ID
 * @returns RTC配置对象，包含appId、roomId、uid和token
 */
export async function generateRtcToken(roomId: string) {
  return request<{
    appId: string;
    roomId: string;
    userName: string;
    uid: string;
    token: string;
  }>({
    url: '/generate-rtc-token',
    method: 'POST',
    params: { roomId },
  });
}
